/**
 * @description:
 * @return {*}
 */
import axios from 'axios'
import { setBaseUrl } from './requestUrl'


/**
 * @description: 1.创建请求实例
 */
const instance = axios.create({
  baseURL: setBaseUrl(process.env.NODE_ENV), //配置默认请求地址
  timeout: 50000, //配置请求超时
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// async 用于申明一个 function 是异步的，而 await 用于等待一个异步方法执行完成。await 只能出现在 async 函数中

/**
 * @description: 2.封装get请求方法
 * @param {*} url 请求的地址
 * @param {*} params get请求参数
 * @param {*} method 请求方式
 * @return {*}
 */

export const getHttp = async (url = '', params = {}, method = 'get') => {
  const result = await instance[method](url, { params })
  return result
}

/**
 * @description: 3.封装post请求方法
 * @param {*} url 请求的地址
 * @param {*} data post请求参数
 * @param {*} method 请求方式
 * @return {*}
 */
export const postHttp = async (url = '', data = {}, method = 'post') => {
  const result = await instance[method](url, data)
  return result
}
export const postHttpStr = async (url = '', data = '', method = 'post') => {
  const result = await instance[method](url, data)
  return result
}
/**
 * @description: 4.put请求
 * @param {*} url
 * @param {*} data
 * @param {*} method
 * @return {*}
 */
export const putHttp = async (url = '', data = {}, method = 'put') => {
  const result = await instance[method](url, data)
  return result
}

/**
 * @description: 4.delete请求
 * @param {*} url
 * @param {*} data
 * @param {*} method
 * @return {*}
 */
export const deleteHttp = async (url = '', data = {}, method = 'delete') => {
  const result = await instance[method](url, data)
  return result
}

// http request 拦截器
instance.interceptors.request.use(
  (config) => {
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

// http response 拦截器
instance.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    return Promise.reject(error)
  }
)

